package com.gc.web.controller.api;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import com.gc.business.domain.*;
import com.gc.business.service.*;
import com.gc.common.constant.BusinessConstants;
import com.gc.common.constant.Constants;
import com.gc.common.utils.StringUtils;
import com.gc.framework.web.base.ApiBaseController;
import com.gc.system.domain.SysRole;
import com.gc.system.domain.SysUser;
import com.gc.system.service.ISysDictDataService;
import com.gc.system.service.ISysUserService;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 电梯 控制层
 *
 * @author liujinteng
 * @date 2020-11-13
 */
@Slf4j
@Controller
@RequestMapping("/api/elevatorInfo")
public class ApiElevatorInfoController extends ApiBaseController {

    @Autowired
    private IElevatorInfoService elevatorInfoService;

    @Autowired
    private ISysDictDataService dictDataService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ICommunityManageService communityManageService;

    @Autowired
    private IElevatorInstallService elevatorInstallService;

    @Autowired
    private IElevatorBrandService elevatorBrandService;

    @Autowired
    private IElevatorModelService elevatorModelService;

    /**
     * 公司用户可以查看的小区列表(名称搜索)
     *
     * @param token
     * @param communityManage
     */
    @GetMapping("/findCommunityByToken")
    @ResponseBody
    public Map<String, Object> findCommunityByToken(String token, CommunityManage communityManage, Integer pageNum, Integer pageSize) {
        SysUser sysUser = userService.selectUserById(getUserId(token));
        List<CommunityManage> communityManageList = communityManageService.searchCommunityList(sysUser, communityManage, pageNum, pageSize);
        Map<String, Object> mapReturn = new HashMap<>();
        mapReturn.put("pageNum", pageNum);
        mapReturn.put("list", communityManageList);
        mapReturn.put("total", new PageInfo<>(communityManageList).getTotal());
        return success(mapReturn);
    }

    /**
     * 小区下的电梯
     *
     * @param communityId
     */
    @GetMapping("/findElevatorInfoByCommunityId")
    @ResponseBody
    public Map<String, Object> findElevatorInfoByCommunityId(String token,Long communityId, Integer pageNum, Integer pageSize) {
        if (communityId == null) {
            return error(Constants.UNVERIFY, "参数错误:communityId为空");
        }
        startPage(pageNum, pageSize, "create_time DESC");
        List<ElevatorInfo> elevatorInfoList = elevatorInfoService.selectListByCommityId(communityId);
        Map<String, Object> mapReturn = new HashMap<>();
        mapReturn.put("pageNum", pageNum);
        mapReturn.put("list", elevatorInfoList);
        mapReturn.put("total", new PageInfo<>(elevatorInfoList).getTotal());
        return success(mapReturn);
    }

    /**
     * 公司用户直接查询电梯列表(暂留)
     *
     * @param token
     * @param elevatorInfo
     */
    @GetMapping("/list")
    @ResponseBody
    public Map<String, Object> list(String token, ElevatorInfo elevatorInfo) {
        List<ElevatorInfo> elevatorInfoList = new ArrayList<>();
        SysUser sysUser = userService.selectUserById(getUserId(token));
        //无归属ID，为平台管理人员,返回空
        if (sysUser == null || StringUtils.isNull(sysUser.getAttrId())) {
            return success(elevatorInfoList);
        }
        SysRole sysRole = userService.checkUserRoleByAttrId(sysUser.getAttrId());
        if (sysRole == null || StringUtils.isEmpty(sysRole.getRoleKey()) || !(sysRole.getRoleKey().equals(BusinessConstants.COMPANY))) {
            return error(Constants.UNVERIFY, "角色错误");
        }
        //查询该用户所在公司底下的社区
        List<CommunityManage> communityManageList = communityManageService.selectCommunityByAttrId(sysUser.getAttrId());
        if (communityManageList == null || communityManageList.size() == 0) {
            return success(elevatorInfoList);
        }
        List<Long> collect = communityManageList.stream().map(CommunityManage::getCommunityId).collect(Collectors.toList());
        return success(elevatorInfoService.list(elevatorInfo, collect));
    }

    /**
     * 电梯基础信息
     *
     * @param elevatorId
     */
    @GetMapping("/elevatorBaseInfo")
    @ResponseBody
    public Map<String, Object> elevatorBaseInfo(Long elevatorId) {
        if (elevatorId == null) {
            return error(Constants.UNVERIFY, "elevatorId为空");
        }
        ElevatorInfo elevatorInfo = elevatorInfoService.getById(elevatorId);
        //建筑类型
        if (StringUtils.isNotEmpty(elevatorInfo.getBuildType())) {
            elevatorInfo.setBuildType(dictDataService.selectDictDataByType("business_build_type", elevatorInfo.getBuildType()));
        }
        //电梯分类(直梯/扶梯)
        if (StringUtils.isNotEmpty(elevatorInfo.getElevatorType())) {
            if (elevatorInfo.getElevatorType().equals("0")) {
                elevatorInfo.setElevatorType("直梯");
            } else if (elevatorInfo.getElevatorType().equals("1")) {
                elevatorInfo.setElevatorType("扶梯");
            }
        }
        //电梯类型
        if (StringUtils.isNotEmpty(elevatorInfo.getStraightElevatorType())) {
            if (elevatorInfo.getStraightElevatorType().equals("0")) {
                elevatorInfo.setStraightElevatorType("液压电梯");
            } else if (elevatorInfo.getStraightElevatorType().equals("1")) {
                elevatorInfo.setStraightElevatorType("曳引电梯");
            } else if (elevatorInfo.getStraightElevatorType().equals("2")) {
                elevatorInfo.setStraightElevatorType("杂物电梯");
            }
        } else if (StringUtils.isNotEmpty(elevatorInfo.getEscalatorType())) {
            {
                if (elevatorInfo.getEscalatorType().equals("0")) {
                    elevatorInfo.setEscalatorType("自动扶梯");
                }
            }
        }
        //电梯状态
        if (StringUtils.isNotEmpty(elevatorInfo.getElevatorStatus())) {
            elevatorInfo.setElevatorStatus(dictDataService.selectDictDataByType("business_elevator_status", elevatorInfo.getElevatorStatus()));
        }
        //联网状态
        if (StringUtils.isNotEmpty(elevatorInfo.getNetworkStatus())) {
            if (elevatorInfo.getNetworkStatus().equals("0")) {
                elevatorInfo.setNetworkStatus("联网");
            } else if (elevatorInfo.getNetworkStatus().equals("1")) {
                elevatorInfo.setNetworkStatus("未联网");
            }
        }
        return success(elevatorInfo);
    }

    /**
     * 首页电梯地图展示
     */
    @GetMapping("/homeElevatorInfoList")
    @ResponseBody
    public Map<String, Object> homeElevatorInfoList(String token,Integer pageNum, Integer pageSize) {
        List<CommunityManage> communityList = userService.findCommunityByUserId(getUserId(token));
        if (CollUtil.isEmpty(communityList)){
            return success();
        }
        List<Long> collect = communityList.stream().map(CommunityManage::getCommunityId).collect(Collectors.toList());
        startPage(pageNum, pageSize, "create_time DESC");
        ElevatorInfo elevatorInfo = new ElevatorInfo();
        List<ElevatorInfo> elevatorInfoList = elevatorInfoService.list(elevatorInfo,collect);
        Map<String, Object> mapReturn = new HashMap<>();
        mapReturn.put("pageNum", pageNum);
        mapReturn.put("list", elevatorInfoList);
        mapReturn.put("total", new PageInfo<>(elevatorInfoList).getTotal());
        return success(mapReturn);
    }

    /**
     * 首页选中电梯查看详情
     */
    @GetMapping("/homeElevatorInfo")
    @ResponseBody
    public Map<String, Object> homeElevatorInfo(Long elevatorId, String latitude, String longitude) {
        if (elevatorId == null) {
            return error(Constants.UNVERIFY, "参数错误:elevatorId为空");
        }
        if (StringUtils.isEmpty(latitude) || StringUtils.isEmpty(longitude)) {
            return error(Constants.UNVERIFY, "参数错误:用户坐标有误");
        }
        ElevatorInfo elevatorInfo = elevatorInfoService.getById(elevatorId);
        if (elevatorInfo == null) {
            return error(Constants.UNVERIFY, "未获取到电梯数据");
        }
        //与电梯之间的距离
        String distance = elevatorInfoService.calculationDistance(latitude, longitude, elevatorInfo.getLatitude(), elevatorInfo.getLongitude());
        elevatorInfo.setBetweenDistance(distance);
        //电梯的地址  中国,陕西省,西安市,雁塔区
        String address = elevatorInfoService.getLatAndLng(elevatorInfo.getLatitude(), elevatorInfo.getLongitude());
        elevatorInfo.setDetailAddress(address);
        //附近的电梯数量(附近2公里)
        Integer elevatorNum = elevatorInfoService.findNeighElevatorNum(elevatorInfo.getLatitude(), elevatorInfo.getLongitude(), "2");
        elevatorInfo.setAroundElevatorNum(String.valueOf(elevatorNum));
        return success(elevatorInfo);
    }

    /**
     * 安装电梯
     */
    @PostMapping("/elevatorInstall")
    @ResponseBody
    public Map<String, Object> elevatorInstall(String token, ElevatorInstall elevatorInstall) {
        SysUser sysUser = userService.selectUserById(getUserId(token));
        if (elevatorInstall.getElevatorId() == null){
            return error(Constants.UNVERIFY,"请选择电梯");
        }
        ElevatorInfo elevatorInfo = elevatorInfoService.getById(elevatorInstall.getElevatorId());
        if (elevatorInfo == null){
            return error(Constants.UNVERIFY,"未查找到电梯数据");
        }
        elevatorInstall.setElevatorName(elevatorInfo.getElevatorName());
        elevatorInstall.setUserId(sysUser.getUserId());
        elevatorInstall.setCreateBy(sysUser.getUserName());
        elevatorInstall.setCreateTime(DateUtil.date());
        if (elevatorInstallService.save(elevatorInstall)) {
            return success(elevatorInstall);
        }
        return error(Constants.UNVERIFY, "安装失败");
    }

    /**
     * 安装电梯记录列表
     *
     * @param token
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("/elevatorInstallRecord")
    @ResponseBody
    public Map<String, Object> elevatorInstallRecord(String token, Integer pageNum, Integer pageSize) {
        //获取用户
        SysUser sysUser = userService.selectUserById(getUserId(token));
        String userRoles = userService.selectUserRole(sysUser.getUserId());
        List<ElevatorInstall> elevatorInstallList = new ArrayList<>();
        SysRole sysRole = userService.checkUserRoleByAttrId(sysUser.getAttrId());
        if (sysRole == null || StringUtils.isEmpty(sysRole.getRoleKey()) || !(sysRole.getRoleKey().equals(BusinessConstants.COMPANY))) {
            return error(Constants.UNVERIFY, "角色错误");
        }
        //不是维保经理只能查看自己的安装记录
        ElevatorInstall install = new ElevatorInstall();
        if (!userRoles.contains(BusinessConstants.KEEP_MANAGER)) {
            install.setUserId(sysUser.getUserId());
            startPage(pageNum, pageSize, "create_time DESC");
            elevatorInstallList = elevatorInstallService.list(install);
        } else {
            install.setCompanyId(sysUser.getAttrId());
            startPage(pageNum, pageSize, "create_time DESC");
            elevatorInstallList = elevatorInstallService.list(install);
        }
        elevatorInstallList.forEach(elevatorInstall -> {
            if (StringUtils.isNotEmpty(elevatorInstall.getElevatorBrand())){
                ElevatorBrand brand = elevatorBrandService.getById(elevatorInstall.getElevatorBrand());
                if (brand == null){
                    elevatorInstall.setElevatorBrand("");
                }else {
                    elevatorInstall.setElevatorBrand(brand.getBrandName());
                }
            }
            if (StringUtils.isNotEmpty(elevatorInstall.getElevatorModel())){
                ElevatorModel model = elevatorModelService.getById(elevatorInstall.getElevatorModel());
                if (model == null){
                    elevatorInstall.setElevatorModel("");
                }else {
                    elevatorInstall.setElevatorModel(model.getModelName());
                }
            }
        });
        Map<String, Object> mapReturn = new HashMap<>();
        mapReturn.put("pageNum", pageNum);
        mapReturn.put("list", elevatorInstallList);
        mapReturn.put("total", new PageInfo<>(elevatorInstallList).getTotal());
        return success(mapReturn);
    }
}
